package com.bosch.in.rtp1.ept.manager.impl;

import java.sql.SQLException;
import java.util.List;

import com.bosch.in.rtp1.ept.constant.ModifiedLinksContanst;
import com.bosch.in.rtp1.ept.dao.LinkListDao;
import com.bosch.in.rtp1.ept.manager.LinkListManager;
import com.bosch.in.rtp1.ept.model.dto.Link;
import com.bosch.in.rtp1.ept.util.ConverterUtility;
import com.bosch.in.rtp1.ept.util.DaoFactory;
import com.bosch.in.rtp1.ept.util.ehcache.EhcacheFactory;

public class LinkListManagerImpl implements LinkListManager{

    
	/**
	 * used to manage connection
	 */
	private DBConnectionManager dbManager;

	private LinkListDao linkListDao;
	
	public LinkListManagerImpl()
	{
		
	}
	
	@Override
	public List<Link> getLinkList() throws SQLException {
		try
		{
			return this.getLinkListLocal();
		}
		finally
		{
			if (dbManager != null) {
				dbManager.close();
			}
		}
	}
	
	@Override
	public String updateLinks(List<Link> links) throws SQLException {
		String errorMsg = "";
		try{
			if (links.size()>0)
			{
				
				// reformat link list
				links = ConverterUtility.formatProtocal(links);
				//errorMsg = isValidFileLink(links);
				if (errorMsg.isEmpty()) {
					// lazy init connection
					init();
					for (int i=0;i<links.size();++i)
					{
						Link link = links.get(i);
						//new object
						if (link.getStatus() == ModifiedLinksContanst.NEW_LINK_STATUS)
						{
							linkListDao.insertLink(link);
						}
						else if (link.getStatus() == ModifiedLinksContanst.DELETED_LINK_STATUS)
						{
							linkListDao.deleteLink(link);
						}
						else 
						{
							linkListDao.updateLink(link);
						}
					}
					//invalidate cache
					EhcacheFactory.getLinkList().invalidate();
				}
			}
			
		}
		finally {
			if (dbManager != null) {
				dbManager.commit();
				dbManager.close();
			}
		}
		return errorMsg;
	}
	
/***********PRIVATE METHOD****************/
	
	/**
	 * lazy initialize connection when we really need to interact with database and in case 
	 * data can't be found in caching system.
	 * @throws SQLException
	 */
	private void init() throws SQLException {
		if (dbManager == null) {
			dbManager = new DBConnectionManager();
			linkListDao = DaoFactory.getInstance().getLinkListDao(dbManager.getConnection());
		}
	}

	private List<Link> getLinkListLocal() throws SQLException {
		// try to load eqpType list from cache	
		List<Link> links = EhcacheFactory.getLinkList().get(ModifiedLinksContanst.LINK_LIST_CACHE);
		if (links == null)
			{
				// lazy init connection
				init();
				// load eqptype list from database if it is not in cache  
				links = linkListDao.getLinkList();
				//put eqptype list into cache
				if (links.size()>0)
				{
					EhcacheFactory.getLinkList().put(ModifiedLinksContanst.LINK_LIST_CACHE, links);
				}
			}
		return links;
	}

}
